package com.aiatomic.couting.templates;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.aiatomic.couting.IConstant;
import com.aiatomic.couting.R;
import com.aiatomic.couting.models.TemplateEntity;
import com.aiatomic.couting.models.TemplateGroupEntity;
import com.aiatomic.couting.util.AppUtils;
import com.aiatomic.couting.util.HttpUtils;
import com.aiatomic.couting.util.SystemUtil;
import com.aiatomic.couting.widgets.LoadingDialog;
import com.aiatomic.couting.widgets.TemplateAdapter;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

public class OnlineTemplatesFragment extends Fragment {
	private View view;
	private LoadingDialog dialog;
	private TemplateAdapter adapter;
	private ListView listView;

	public TemplateAdapter getAdapter() {
		return adapter;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_online_templates, container, false);
		dialog = new LoadingDialog(getActivity());
		check_templates();
		return view;
	}

	private void initUI(JSONArray templates) {
		List<TemplateEntity> localTpls = new ArrayList<TemplateEntity>();

		SystemUtil.getAllLocalStoreTemplates(getContext(),localTpls);

		listView = (ListView) view.findViewById(R.id.lv_configurations_assets);
		List<TemplateGroupEntity> groups = new ArrayList<TemplateGroupEntity>();
		Map<Integer, TemplateGroupEntity> tMap = new HashMap<Integer, TemplateGroupEntity>();
		for (int i = 0; i < templates.length(); i++) {
			try {
				JSONObject tpl = templates.getJSONObject(i);
				int group_id = tpl.getInt("group_id");
				TemplateEntity entity = new TemplateEntity();
				entity.setDesc(tpl.getString("desc"));
				entity.setGroup_id(group_id);
				entity.setGroup_name(tpl.getString("group_name"));
				entity.setGroup_pic(tpl.getString("group_pic"));
				entity.setPlatform(tpl.getInt("platform"));
				entity.setIs_recommend(tpl.getInt("is_recommend") == 1 ? true : false);
				entity.setName(tpl.getString("name"));
				entity.setPic(tpl.getString("pic"));
				entity.setPos(tpl.getInt("pos"));
				entity.setRes_url(tpl.getString("res_url"));
				entity.setSb_template_id(tpl.getInt("sb_template_id"));
				entity.setType(tpl.getInt("type"));
				entity.settKey(tpl.getString("t_key"));
				entity.setVersion(tpl.getString("version"));
				entity.setShape(tpl.getString("shape"));
				entity.setDownload(localTpls.contains(entity));
				if (tMap.containsKey(group_id)) {
					TemplateGroupEntity group = tMap.get(group_id);
					group.getTemplates().add(entity);
				} else {
					TemplateGroupEntity group = new TemplateGroupEntity();
					group.setGroup_id(group_id);
					group.setGroup_name(tpl.getString("group_name"));
					group.setGroup_pic(tpl.getString("group_pic"));
					group.setPlatform(tpl.getInt("platform"));
					group.getTemplates().add(entity);
					tMap.put(group_id, group);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		for(int key:tMap.keySet()){
			groups.add(tMap.get(key));
		}
		adapter = new TemplateAdapter(getActivity(), R.layout.list_item_count_template, groups);
		adapter.sort(new Comparator< TemplateGroupEntity>(){

			@Override
			public int compare(TemplateGroupEntity lhs, TemplateGroupEntity rhs) {
				return lhs.getGroup_id()-rhs.getGroup_id();
			}
		});
		listView.setAdapter(adapter);
	};

	private void check_templates() {
		dialog.setMessage(getString(R.string.loading_msg1));
		dialog.show();
		Map<String, String> params = new HashMap<String, String>();
		params.put("platform", String.valueOf(IConstant.PLATFORM));
		params.put("aid", AppUtils.aid);
		params.put("client_version", SystemUtil.getAppVersion(getActivity()));
		params.put("time", String.valueOf(Calendar.getInstance().getTimeInMillis()));
		params.put("channel", String.valueOf(AppUtils.channel));
		params.put("sign", HttpUtils.md5(params.get("aid") + params.get("time") + params.get("client_version")
				+ params.get("platform") + params.get("channel") + IConstant.NORMAL_MD5_KEY));
		params.put("ssign", HttpUtils.md5(params.get("aid") + params.get("time") + params.get("client_version")
				+ params.get("platform") + params.get("channel") + AppUtils.sKey));
		HttpUtils.post(new Handler() {

			@Override
			public void handleMessage(Message msg) {
				dialog.cancel();
				if (msg.what == HttpUtils.CODE_SUCCESS_RQ_100) {
					try {
						JSONObject json = new JSONObject(msg.obj.toString());
						if (json.getInt("code") == HttpUtils.RET_SUCCESS) {
							JSONArray templates = json.getJSONArray("templates");
							initUI(templates);
						} else {
							Toast toast = Toast.makeText(getActivity(), json.getString("msg"), Toast.LENGTH_LONG);
							toast.setGravity(Gravity.CENTER, 0, 0);
							toast.show();
						}
					} catch (JSONException e) {
						e.printStackTrace();
						Log.e("", msg.obj.toString());
						Toast toast = Toast.makeText(getActivity(),
								getActivity().getResources().getString(R.string.server_format_error),
								Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
				} else {
					getActivity().findViewById(R.id.vp_templates).setVisibility(View.GONE);
					getActivity().findViewById(R.id.noInternetContent).setVisibility(View.VISIBLE);
				}
			}

		}, AppUtils.url + "/v/cindex/check_templates/", params);
	}
}
